home *** CD-ROM | disk | FTP | other *** search
- #include "PseudoRandom.h"
-
- UInt32 RandomLong();
- UInt32 RandomRandomLong();
-
- UInt32 gRandomSeed = 0;
-
- void SetRandomSeed(UInt32 seed)
- {
- gRandomSeed = seed;
- }
-
- UInt32 RandomLong()
- {
- gRandomSeed = (gRandomSeed * 1103515245) + 12345;
-
- return gRandomSeed;
- }
-
- //
- // No, I'm not sure this makes the output any more random
- // (it does spread the TickCount bits around, though)
- //
- UInt32 RandomRandomLong()
- {
- return RandomLong() ^ ((RandomLong() << 8) & 0x00FFFF00) ^ (RandomLong() << 16);
- }
-
- //
- // No, I'm not sure this makes the output any more random
- //
- UInt32 PseudoRandomLong()
- {
- UInt32 rand1 = RandomRandomLong();
- UInt32 rand2 = RandomRandomLong();
- UInt32 mask = RandomRandomLong();
-
- //
- // Any set bit in 'mask' selects the bit from rand1;
- // any clear bit in 'mask' selects the bit from rand2.
- //
- return ((rand1 ^ rand2) & mask) ^ rand2;
- }
-
- UInt32 PseudoRandomFromZeroToN(UInt32 n)
- {
- UInt32 result = 0;
-
- //
- // Special checking for N == max long integer
- // (Speed optimization, plus avoids a divide-by-zero)
- //
- if(n == 0xFFFFFFFF)
- result = PseudoRandomLong();
- if(n > 0)
- {
- //
- // Some might find it acceptable to simply modulo
- // the result with n. This is no good, however,
- // because it does not give a good linear distribution.
- // There will (usually) be some section at the top
- // of the number space that maps to the lower portion
- // of n, making small values of n oh-so-slightly more
- // probably than the high values of n.
- //
- UInt32 highestAcceptable = ((0xFFFFFFFF / (n+1)) * (n+1)) - 1;
-
- //
- // Trim off the top end of the range to obtain a
- // flat linear distribution.
- //
- // n.b. This assumes that PseudoRandomLong returns
- // numbers distributed linearly, something that I
- // hope is true, but certainly have not proved.
- //
- do
- {
- result = PseudoRandomLong();
- } while(result > highestAcceptable);
-
- //
- // Now that we have a linear distribution,
- // modulo by (n+1) to put the range in
- // 0-n.
- //
- result %= (n+1);
- }
-
- return result;
- }
-
- UInt32 PseudoRandomFromMToN(UInt32 m, UInt32 n)
- {
- return m < n ? PseudoRandomFromZeroToN(n - m) + m : m;
- }
-